import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus';
import viteCompression from 'vite-plugin-compression';
import { buildConfig } from './src/utils/build';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import AutoImport from 'unplugin-auto-import/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

// process.env.VUE_APP_PROXY_TARGET = 'https://star.adaix.cn/angis-api/';
process.env.VUE_APP_PROXY_TARGET = 'http://127.0.0.1:8881/';
const pathResolve = (dir: string) => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		resolve: { alias },
		plugins: [
			vue(),
			vueSetupExtend(),
			viteCompression(),
			JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.cdn() : null,
			AutoImport({
				// 导入 Vue 函数，如：ref, reactive, toRef 等
				imports: ['vue', '@vueuse/core', 'pinia', 'vue-router', 'vue-i18n'],
				eslintrc: {
					enabled: false,
					filepath: './.eslintrc-auto-import.json',
					globalsPropValue: true,
				},
				resolvers: [
					ElementPlusResolver(),
				  ],
				dts: "src/auto-import.d.ts"
			}),
		],
		root: process.cwd(),
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT as unknown as number,
			open: env.VITE_OPEN,
			hmr: true,
			proxy: {
				'/angis-api': {
					target: process.env.VUE_APP_PROXY_TARGET,
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/angis-api/, ''),
				},
			},
		},
		build: {
			outDir: 'dist',
			minify: 'terser',
			chunkSizeWarningLimit: 1500,
			terserOptions: {
				compress: {
					keep_infinity: true, // 防止 Infinity 被压缩成 1/0，这可能会导致 Chrome 上的性能问题
					drop_console: true, // 生产环境去除 console
					drop_debugger: true, // 生产环境去除 debugger
				},
				format: {
					comments: false, // 删除注释
				},
			},
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: (assetInfo: any) => {
						const info = assetInfo.name.split('.');
						let extType = info[info.length - 1];
						// console.log('文件信息', assetInfo.name)
						if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
							extType = 'assets/media';
						} else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {
							extType = 'assets/img';
						} else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
							extType = 'assets/fonts';
						}
						return `${extType}/[name].[hash].[ext]`;
					},
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().split('node_modules/')[1].split('/')[0].toString();
						}
					},
				},
				external: JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.external : [],
			},
		},
		css: { preprocessorOptions: { css: { charset: false } } },
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__VERSION__: JSON.stringify(process.env.npm_package_version),
			EDITTYPE: JSON.stringify('edit'),
			ADDTYPE: JSON.stringify('add'),
		},
		// 预加载项目必需的组件
		optimizeDeps: {
			include: [
				'vue',
				'vue-router',
				'element-plus',
				'pinia',
				'axios',
				'@vueuse/core',
				'sortablejs',
				'path-to-regexp',
				'vue-i18n',
				'nprogress',
				'qs',
				'path-browserify',
				'@element-plus/icons-vue',
				'element-plus/es/locale/lang/zh-cn',
				'element-plus/es/locale/lang/en',
				'element-plus/es/components/form/style/css',
				'element-plus/es/components/form-item/style/css',
				'element-plus/es/components/button/style/css',
				'element-plus/es/components/input/style/css',
				'element-plus/es/components/input-number/style/css',
				'element-plus/es/components/switch/style/css',
				'element-plus/es/components/upload/style/css',
				'element-plus/es/components/menu/style/css',
				'element-plus/es/components/col/style/css',
				'element-plus/es/components/icon/style/css',
				'element-plus/es/components/row/style/css',
				'element-plus/es/components/tag/style/css',
				'element-plus/es/components/dialog/style/css',
				'element-plus/es/components/loading/style/css',
				'element-plus/es/components/radio/style/css',
				'element-plus/es/components/radio-group/style/css',
				'element-plus/es/components/popover/style/css',
				'element-plus/es/components/scrollbar/style/css',
				'element-plus/es/components/tooltip/style/css',
				'element-plus/es/components/dropdown/style/css',
				'element-plus/es/components/dropdown-menu/style/css',
				'element-plus/es/components/dropdown-item/style/css',
				'element-plus/es/components/sub-menu/style/css',
				'element-plus/es/components/menu-item/style/css',
				'element-plus/es/components/divider/style/css',
				'element-plus/es/components/card/style/css',
				'element-plus/es/components/link/style/css',
				'element-plus/es/components/breadcrumb/style/css',
				'element-plus/es/components/breadcrumb-item/style/css',
				'element-plus/es/components/table/style/css',
				'element-plus/es/components/tree-select/style/css',
				'element-plus/es/components/table-column/style/css',
				'element-plus/es/components/select/style/css',
				'element-plus/es/components/option/style/css',
				'element-plus/es/components/pagination/style/css',
				'element-plus/es/components/tree/style/css',
				'element-plus/es/components/alert/style/css',
				'element-plus/es/components/radio-button/style/css',
				'element-plus/es/components/checkbox-group/style/css',
				'element-plus/es/components/checkbox/style/css',
				'element-plus/es/components/tabs/style/css',
				'element-plus/es/components/tab-pane/style/css',
				'element-plus/es/components/rate/style/css',
				'element-plus/es/components/date-picker/style/css',
				'element-plus/es/components/notification/style/css',
				'element-plus/es/components/image/style/css',
				'element-plus/es/components/statistic/style/css',
				'element-plus/es/components/watermark/style/css',
				'element-plus/es/components/config-provider/style/css',
				'element-plus/es/components/text/style/css',
				'element-plus/es/components/drawer/style/css',
				'element-plus/es/components/color-picker/style/css',
				'element-plus/es/components/backtop/style/css',
				'element-plus/es/components/message-box/style/css',
				'element-plus/es/components/skeleton/style/css',
				'element-plus/es/components/skeleton/style/css',
				'element-plus/es/components/skeleton-item/style/css',
				'element-plus/es/components/badge/style/css',
				'element-plus/es/components/steps/style/css',
				'element-plus/es/components/step/style/css',
				'element-plus/es/components/avatar/style/css',
				'element-plus/es/components/descriptions/style/css',
				'element-plus/es/components/descriptions-item/style/css',
				'element-plus/es/components/checkbox-group/style/css',
				'element-plus/es/components/progress/style/css',
				'element-plus/es/components/image-viewer/style/css',
				'element-plus/es/components/empty/style/css',
				'element-plus/es/components/message/style/css',
				'element-plus/es/components/timeline/style/css',
				'element-plus/es/components/timeline-item/style/css',
			],
		},
	};
});

export default viteConfig;
